package com.keruyun.talent.basic.component.redis;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.Assert;

/**
 * spring整合redis template lock
 * 
 * @author admin
 * @version [版本号, 2017年8月15日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class SpringRedisTemplateLock extends RedisLock {

	private RedisTemplate<String, Long> redisTemplate;

	public SpringRedisTemplateLock(RedisTemplate<String, Long> redisTemplate, String lockKey, int retryTimes, int expireMsecs) {
		super(lockKey, retryTimes, expireMsecs);
		Assert.notNull(redisTemplate, "redisTemplate 为空");
		this.redisTemplate = redisTemplate;
	}

	@Override
	protected void deleteKey() {
		redisTemplate.delete(getLockKey());

	}

	@Override
	protected Long get() {
		ValueOperations<String, Long> operations = redisTemplate.opsForValue();
		return operations.get(getLockKey());

	}

	@Override
	protected Boolean setNx(Long value) {
		ValueOperations<String, Long> operations = redisTemplate.opsForValue();
		return operations.setIfAbsent(getLockKey(), value);
	}

	@Override
	protected Long getAndSet(Long value) {
		ValueOperations<String, Long> operations = redisTemplate.opsForValue();
		return operations.getAndSet(getLockKey(), value);
	}

}
